<template>
  <div class="config-list">
    <div class="header">
      <Input
        v-model="param.key"
        placeholder="请输入关键字..."
        style="width: 300px"
      />
      <Button type="primary" @click="handleSearch" style="margin: 0 15px"
        >查询</Button
      >
      <Button @click="showAdd = !showAdd">新建</Button>
    </div>
    <div class="table-con" ref="tableCon">
      <Table
        border
        :columns="columns"
        :max-height="tableHeight"
        :data="tableData"
      ></Table>
    </div>
    <div class="page-con">
      <NrPage
        :current="param.page"
        :total="total"
        :page-size="param.pageSize"
        @on-change="handlePageChange"
        @on-page-size-change="handleSizeChange"
      >
      </NrPage>
    </div>
    <Modal
      v-model="showAdd"
      title="添加新配置"
      @on-cancel="showAdd = false"
      @on-ok="handleAdd"
    >
      <Form :model="formData" :rules="ruleValidate">
        <FormItem label="配置名称" prop="name">
          <Input v-model="formData.name" />
        </FormItem>
        <FormItem label="配置标识" prop="path">
          <Input v-model="formData.path" />
        </FormItem>
        <FormItem label="配置编码" prop="code">
          <Input v-model="formData.code" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { searchConfig, saveConfig, deleteConfig } from "@/api";
export default {
  props: {
    curModal: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      total: 0,
      showAdd: false,
      tableHeight: 600,
      curConfig: {},
      tableData: [],
      formData: {
        name: "",
        path: "",
        config: "",
        detail: "",
      },
      ruleValidate: {
        name: [
          {
            required: true,
            message: "请输入配置名！",
            trigger: "blur",
          },
        ],
        path: [
          {
            required: true,
            message: "请输入标识！",
            trigger: "blur",
          },
        ],
      },
      param: {
        page: 1,
        pageSize: 15,
        key: "",
      },
      columns: [
        {
          title: "序号",
          type: "index",
          width: 100,
        },
        {
          title: "配置标识",
          key: "path",
        },
        {
          title: "配置名称",
          key: "name",
        },
        {
          title: "配置说明",
          key: "detail",
          render: (h, param) => {
            let { key } = param.column;
            let value = param.row[key];
            let canEditor =
              this.$store.getters.userInfo.type === "admin" ||
              this.$store.getters.userInfo.id === param.row.user_id;
            if (canEditor) {
              return (
                <Input
                  value={value}
                  on-on-blur={(event) => {
                    let value = event.target.value;

                    if (value && value.includes("https://")) {
                      saveConfig({
                        id: param.row._id,
                        detail: value,
                      });
                    }
                  }}
                />
              );
            } else {
              return <span>{value}</span>;
            }
          },
        },
        {
          title: "操作",
          align: "center",
          render: (h, param) => {
            return (
              <span>
                <Button
                  type="text"
                  on-click={() => {
                    this.$emit("change-tab", "configEditor", param.row);
                  }}
                >
                  编辑
                </Button>
                <Button
                  type="text"
                  on-click={() => {
                    this.handleDelete(param);
                  }}
                >
                  删除
                </Button>
              </span>
            );
          },
        },
      ],
    };
  },
  watch: {
    curModal() {
      if (this.curModal === "configList") {
        if (this.tableHeight === 600) {
          setTimeout(() => {
            this.tableHeight = this.$refs.tableCon.clientHeight - 5;
          }, 1000);
        }
      }
    },
  },
  mounted() {
    this.handleSearch();
  },
  methods: {
    randomString(len) {
      len = len || 32;
      let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = $chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },

    handlePageChange(page) {
      this.param.pageIndex = page;
      this.handleSearch();
    },

    handleSizeChange(size) {
      this.param.pageSize = size;
      this.handleSearch();
    },

    async handleDelete(param) {
      this.loading = true;
      await deleteConfig(param.row._id);
      this.handleSearch();
      this.loading = false;
    },

    async handleSearch() {
      this.loading = true;
      let res = await searchConfig({
        ...this.param,
        pageIndex: this.param.pageIndex - 1,
      });
      this.tableData = res.rows;
      this.total = res.totalElements;
      this.loading = false;
    },

    async handleAdd() {
      if (!this.formData.code) {
        this.formData.code = this.randomString();
      }
      await saveConfig(this.formData);
      await this.handleSearch();
      this.formData = {
        name: "",
        path: "",

        config: "",
        detail: "",
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.config-list {
  width: 100%;
  height: 100%;

  background: white;
  padding: 0 15px;
  display: flex;
  flex-direction: column;
  .header {
    width: 100%;
    height: 50px;
    line-height: 50px;
    position: relative;
  }
  .table-con {
    width: 100%;
    flex: 1;
  }
  .page-con {
    line-height: 50px;
    height: 50px;
    text-align: right;
  }
}
</style>
